package com.sheyu.mall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.sheyu.common.exception.NoStockException;
import com.sheyu.common.to.OrderTo;
import com.sheyu.common.to.SkuHasStockVo;
import com.sheyu.common.to.StockLockedTo;
import com.sheyu.common.to.mq.StockDetailTo;
import com.sheyu.common.utils.R;
import com.sheyu.mall.ware.entity.WareOrderTaskDetailEntity;
import com.sheyu.mall.ware.entity.WareOrderTaskEntity;
import com.sheyu.mall.ware.feign.OrderFeignService;
import com.sheyu.mall.ware.service.WareOrderTaskDetailService;
import com.sheyu.mall.ware.service.WareOrderTaskService;
import com.sheyu.mall.ware.vo.OrderItemVo;
import com.sheyu.mall.ware.vo.OrderVo;
import com.sheyu.mall.ware.vo.WareSkuLockVo;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sheyu.common.utils.PageUtils;
import com.sheyu.common.utils.Query;

import com.sheyu.mall.ware.dao.WareSkuDao;
import com.sheyu.mall.ware.entity.WareSkuEntity;
import com.sheyu.mall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;

@RabbitListener(queues = "stock.release.stock.queue")
@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {


    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    WareOrderTaskService wareOrderTaskService;

    @Autowired
    WareSkuService wareSkuService;

    @Autowired
    WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    WareSkuDao wareSkuDao;

    @Autowired
    OrderFeignService orderFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();

        String wareId = (String) params.get("wareId");
        if (StringUtils.isNotBlank(wareId)){
            wrapper.eq("ware_id",wareId);
        }
        String skuId = (String) params.get("skuId");
        if (StringUtils.isNotBlank(skuId)){
            wrapper.eq("sku_id",skuId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuHasStockVo> getSkuHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> skuHasStockVos = skuIds.stream().map(skuId->{
            Long count = this.baseMapper.getSkuStock(skuId);
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            skuHasStockVo.setSkuId(skuId);
            skuHasStockVo.setHasStock(count==null?false:count>0);
            return skuHasStockVo;
        }).collect(Collectors.toList());
        return skuHasStockVos;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean orderLockStock(WareSkuLockVo vo) {

        /**
         *
         */
        WareOrderTaskEntity wareOrderTaskEntity = new WareOrderTaskEntity();
        wareOrderTaskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskEntity.setCreateTime(new Date());
        wareOrderTaskService.save(wareOrderTaskEntity);

        List<OrderItemVo> locks = vo.getLocks();
        //找商品在哪个仓库有库存

        List<SkuWareHasStock> skuWareHasStocks = locks.stream().map(orderItemVo -> {
            SkuWareHasStock skuWareHasStock = new SkuWareHasStock();
            skuWareHasStock.setNum(orderItemVo.getCount());
            Long skuId = orderItemVo.getSkuId();
            skuWareHasStock.setSkuId(skuId);
            List<Long> wareIds = wareSkuDao.listWareIdHasSkuStock(skuId);
            skuWareHasStock.setWareId(wareIds);
            return skuWareHasStock;
        }).collect(Collectors.toList());

        for(SkuWareHasStock skuWareHasStock:skuWareHasStocks){
            boolean skuStocked = false;
            Long skuId = skuWareHasStock.getSkuId();
            List<Long> wareIds = skuWareHasStock.getWareId();
            if (org.springframework.util.StringUtils.isEmpty(wareIds)){
                throw  new NoStockException(skuId);
            }

            for(Long wareId:wareIds){
                //1就是返回成功，0就是返回失败
               long count = wareSkuDao.lockSkuStock(skuId,wareId,skuWareHasStock.getNum());

               if(count==1){
                   skuStocked = true;
                   WareOrderTaskDetailEntity wareOrderTaskDetailEntity =  WareOrderTaskDetailEntity.builder()
                           .skuId(skuId)
                           .skuName("")
                           .skuNum(skuWareHasStock.getNum())
                           .taskId(wareOrderTaskEntity.getId())
                           .wareId(wareId)
                           .lockStatus(1)
                           .build();
                   wareOrderTaskDetailService.save(wareOrderTaskDetailEntity);

                   //   告诉MQ锁定库存成功
                   StockLockedTo lockedTo = new StockLockedTo();
                   StockDetailTo detailTo = new StockDetailTo();
                   BeanUtils.copyProperties(wareOrderTaskDetailEntity,detailTo);
                   lockedTo.setId(wareOrderTaskEntity.getId());
                   lockedTo.setDetailTo(detailTo);
                   rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",lockedTo);
                    break;
               }else{

               }

            }
            if (skuStocked == false){
                throw new NoStockException(skuId);
            }
        }
        //3、全部都是锁定成功的
        return true;
    }

    @Override
    public void unlockStock(StockLockedTo to) {

        //库存工作单位id
        StockDetailTo detailTo = to.getDetailTo();
        Long detailId = detailTo.getId();

        /**
         * 解锁
         * 1、查询数据库关于这个订单锁定库存信息
         * 有：证明库存锁定成功
         *  解锁：订单状况
         *  1、没有这个订单，必须解锁库存
         *  2、有这个订单，不一定解锁库存
         *  订单状态：已取消：解锁库存
         *          已支付：不能解锁库存
         */
        WareOrderTaskDetailEntity taskDetailEntity = wareOrderTaskDetailService.getById(detailId);
        if (taskDetailEntity!=null){
            Long id = to.getId();
            WareOrderTaskEntity orderTaskEntity = wareOrderTaskService.getById(id);
            //获取订单号
            String orderSn = orderTaskEntity.getOrderSn();

            R orderData = orderFeignService.getOrderStatus(orderSn);

            if (orderData.getCode()==0){
                OrderVo orderVo = orderData.getData("data",new TypeReference<OrderVo>(){});

                //'订单状态【0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单】',
                if (orderVo == null || orderVo.getStatus()==4){
                    //订单已经取消，可以解锁库存
                    if(taskDetailEntity.getLockStatus() ==1){
                        //当前库存工作单详情状态1，已锁定，但是未解锁才可以解锁
                        unlockStock(detailTo.getSkuId(),detailTo.getWareId(),detailTo.getSkuNum(),detailId);
                    }
                }
            }else{
                throw new RuntimeException("远程调用服务失败");
            }
        }else{
            //无需解锁
        }
    }

    /**
     * 防止订单服务卡顿，导致订单状态消息一直改不了，库存优先到期，查订单状态新建，什么都不处理
     * 导致卡顿的订单，永远都不能解锁库存
     * @param orderTo
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void unlockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();

        //查询
        WareOrderTaskEntity orderTaskEntity = wareOrderTaskService.getOrderTaskByOrderSn(orderSn);

        Long id = orderTaskEntity.getId();
        List<WareOrderTaskDetailEntity> wareOrderTaskDetailEntities = wareOrderTaskDetailService.
                list(new QueryWrapper<WareOrderTaskDetailEntity>()
                        .eq("task_id",id).eq("lock_status",1));
        for (WareOrderTaskDetailEntity taskDetailEntity:wareOrderTaskDetailEntities){
            unlockStock(taskDetailEntity.getSkuId(),
                    taskDetailEntity.getWareId(),
                    taskDetailEntity.getSkuNum(),
                    taskDetailEntity.getId());
        }
    }

    private void unlockStock(Long skuId, Long wareId, Integer skuNum, Long detailId) {
        //库存解锁
        wareSkuDao.unLockStock(skuId,wareId,skuNum);

        //更新工作单的状态
        WareOrderTaskDetailEntity taskDetailEntity = new WareOrderTaskDetailEntity();
        taskDetailEntity.setId(detailId);

        //解锁
        taskDetailEntity.setLockStatus(2);
        wareOrderTaskDetailService.updateById(taskDetailEntity);
    }

    @Data
    class SkuWareHasStock {
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }


}
